Practice Problems on File Handling in C++
Posted on December 18, 2023 by Vishesh Namdev
Python
C
C++
Java
Basic Practice Problems based on chapter which you learn in previous Tutorials.
1. Write a Sentence in File
#include <iostream>
int main() {
// Open a file for writing
std::ofstream outputFile("example.txt");
// Check if the file is successfully opened
if (!outputFile.is_open()) {
std::cerr << "Error opening the file!" << std::endl;
return 1;
}
// Write a sentence to the file
outputFile << "Hello, this is a sentence written to a file in C++." << std::endl;
// Close the file
outputFile.close();
std::cout << "Sentence successfully written to the file." << std::endl;
return 0;
}
int main() {
// Open a file for writing
std::ofstream outputFile("example.txt");
// Check if the file is successfully opened
if (!outputFile.is_open()) {
std::cerr << "Error opening the file!" << std::endl;
return 1;
}
// Write a sentence to the file
outputFile << "Hello, this is a sentence written to a file in C++." << std::endl;
// Close the file
outputFile.close();
std::cout << "Sentence successfully written to the file." << std::endl;
return 0;
}
2. Read the first Line from File
#include <iostream>
#include <iostream>
int main() {
// Open a file for reading
std::ifstream inputFile("example.txt");
// Check if the file is successfully opened
if (!inputFile.is_open()) {
std::cerr << "Error opening the file!" << std::endl;
return 1;
}
// Read the first line from the file
std::string firstLine;
std::getline(inputFile, firstLine);
// Close the file
inputFile.close();
// Display the first line
std::cout << "First line from the file: " << firstLine << std::endl;
return 0;
}
#include <iostream>
int main() {
// Open a file for reading
std::ifstream inputFile("example.txt");
// Check if the file is successfully opened
if (!inputFile.is_open()) {
std::cerr << "Error opening the file!" << std::endl;
return 1;
}
// Read the first line from the file
std::string firstLine;
std::getline(inputFile, firstLine);
// Close the file
inputFile.close();
// Display the first line
std::cout << "First line from the file: " << firstLine << std::endl;
return 0;
}